package com.zdkj.subway.check.controller.subwayRat.reportMondify;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.cache.RedisTemplateConfig;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.Xw_ReportMistakeInfoCtrl;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwStReportErrorAlterAppayDetailMapper;
import com.zdkj.subway.check.mapper.SwStReportErrorAlterAppayMapper;
import com.zdkj.subway.check.mapper.SysRoleMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.impl.subwayRat.reportMondify.ReportMistakeInfoServiceImpl;
import com.zdkj.subway.check.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表差错信息
 */
@RestController
@RequestMapping("/check")
@Slf4j
public class ReportMistakeInfoController {

    @Resource
    private ReportMistakeInfoServiceImpl reportMistakeInfoServiceImpl;
    @Resource
    private CommonController commonController;
    @Resource
    private SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    @Resource
    private SwStReportErrorAlterAppayMapper reportMistakeInfoMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SwStReportErrorAlterAppayDetailMapper swStReportErrorAlterAppayDetailMapper;
    @Resource
    RedisTemplateConfig redisTemplateConfig;
    @Resource
    private Xw_ReportMistakeInfoCtrl xwReportMistakeInfoCtrl;

    /**
     * 报表差错信息查询
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getReportErrorList")
    @ApiOperation(value = "报表差错信息查询", notes = "报表差错信息查询")
    public R getReportErrorList(com.baomidou.mybatisplus.extension.plugins.pagination.Page page, @RequestParam Map<String,Object> param){
        PigxUser user = SecurityUtils.getUser();
        //是否是线网人员
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
        //查询信息
        IPage<SwStReportErrorAlterApply> reportErrorAlterAppays= reportMistakeInfoServiceImpl.getReportErrorList(page,param);
        return R.ok(reportErrorAlterAppays);
    }

    /**
     * 插入报表差错数据
     * @param swStReportErrorAlterApply
     * @param param
     * @return
     */
    @RequestMapping("/addReportError")
    @ApiOperation(value = "插入报表差错数据", notes = "插入报表差错数据")
    public Result addReportError(SwStReportErrorAlterApply swStReportErrorAlterApply, @RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            swStReportErrorAlterApply.setErrorClassification("");
            swStReportErrorAlterApply.setErrorAmount("0");
            swStReportErrorAlterApply.setDelFlag("0");
            swStReportErrorAlterApply.setApplyReason("");
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            swStReportErrorAlterApply.setApplyTime(dff.format(new Date()));
            swStReportErrorAlterApply.setUpdateTime(dff.format(new Date()));
            swStReportErrorAlterApply.setCreateTime(dff.format(new Date()));
            swStReportErrorAlterApply.setCheckStatus("2");
            swStReportErrorAlterApply.setModifyLimitTime(0);
            swStReportErrorAlterApply.setDataSource("");
            swStReportErrorAlterApply.setIsModify("0");
            //加入报表差错
            Integer addReportError = reportMistakeInfoServiceImpl.addReportError(swStReportErrorAlterApply,param);
            if(addReportError<=0){
                result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
        }
        return result;
    }

    /**
     * 删除报表差错数据(逻辑删除，只是改变状态)
     * @param swStReportErrorAlterApply
     * @return
     */
    @RequestMapping("/delReportError")
    @ApiOperation(value = "删除报表差错数据(逻辑删除，只是改变状态)", notes = "删除报表差错数据(逻辑删除，只是改变状态)")
    public Result delReportError(SwStReportErrorAlterApply swStReportErrorAlterApply,String ids){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            SwStReportErrorAlterApply param=new SwStReportErrorAlterApply();
            param.setId(swStReportErrorAlterApply.getId());
            param.setDelFlag(swStReportErrorAlterApply.getDelFlag());
            UpdateWrapper<SwStReportErrorAlterApply> updateWrapper=new UpdateWrapper<>();
            updateWrapper.set("del_flag",swStReportErrorAlterApply.getDelFlag());
            updateWrapper.in("id",ids.split(","));
//            int aff = swStReportErrorAlterAppayMapper.updateById(param);
            int aff = swStReportErrorAlterAppayMapper.update(swStReportErrorAlterApply,updateWrapper);
            if(aff==0){
                result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
                result.appendMsg("未修改数据");
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return result;
    }
    /**
     * 高级删除
     * 删除报表差错数据(逻辑删除，只是改变状态)
     * @param swStReportErrorAlterApply
     * @return
     */
    @RequestMapping("/highDelReportError")
    @ApiOperation(value = "删除报表差错数据(逻辑删除，只是改变状态)", notes = "删除报表差错数据(逻辑删除，只是改变状态)")
    @PreAuthorize("@pms.hasPermission('sw_st_report_error_alter_apply_highdel')")
    public Result highDelReportError(SwStReportErrorAlterApply swStReportErrorAlterApply,String ids){
        PigxUser user = SecurityUtils.getUser();
        Result result=new Result(ResultDetailMsg.OK);
        try {
            SwStReportErrorAlterApply param=new SwStReportErrorAlterApply();
            param.setId(swStReportErrorAlterApply.getId());
            param.setDelFlag(swStReportErrorAlterApply.getDelFlag());
            UpdateWrapper<SwStReportErrorAlterApply> updateWrapper=new UpdateWrapper<>();
            updateWrapper.set("del_flag",swStReportErrorAlterApply.getDelFlag());
            updateWrapper.set("RESERVED1",user.getNikeName());
            updateWrapper.set("RESERVED2", DateFormat.currLocalDateTimeTurnString());
            updateWrapper.in("id",ids.split(","));
            int aff = swStReportErrorAlterAppayMapper.update(swStReportErrorAlterApply,updateWrapper);
            if(aff==0){
                result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
                result.appendMsg("未修改数据");
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
        }
        return result;
    }

    /**
     * 报表差错通知
     * @param param
     * @return
     */
    @RequestMapping("/noticeReport")
    @ApiOperation(value = "报表差错通知", notes = "报表差错通知")
    @Transactional(rollbackFor = Exception.class)
    public Result noticeReport(@RequestBody Map<String,Object> param){
        String ids = String.valueOf(param.get("ids"));
        String swStids = org.apache.commons.lang.StringUtils.strip(ids,"[]");
        Result result=new Result(ResultDetailMsg.OK);
        PigxUser user = SecurityUtils.getUser();
        try {
            UpdateWrapper<SwStReportErrorAlterApply> updateWrapper=new UpdateWrapper<>();
            String notice_status = String.valueOf(param.get("noticeStatus"));
            SwStReportErrorAlterApply swStReportErrorAlterApply = new SwStReportErrorAlterApply();
            swStReportErrorAlterApply.setNoticeStatus(notice_status);
            //swStReportErrorAlterApply.setIsModify("2");
            swStReportErrorAlterApply.setNoticeTime(new Date());
            swStReportErrorAlterApply.setNoticePerson(user.getNikeName());
            swStReportErrorAlterApply.setNoticePersonCode(user.getUserCode());
//            updateWrapper.set("notice_time",new Date());
            updateWrapper.in("id",swStids.split(","));
            int aff = swStReportErrorAlterAppayMapper.update(swStReportErrorAlterApply,updateWrapper);
            if(aff==0){
                result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
                result.appendMsg("未通知成功");
            }
            swStReportErrorAlterAppayMapper.updateMondifyLimitTime(swStids);
            commonController.innerBatch(param);

            //线网通知报表差错后 车站修改加入报表差错状态
            List<SwStReportErrorAlterApply> swStReportErrorAlterApplies = swStReportErrorAlterAppayMapper.selectList(Wrappers.<SwStReportErrorAlterApply>lambdaQuery()
                    .in(SwStReportErrorAlterApply::getId, swStids.split(",")));
            if(CollectionUtil.isNotEmpty(swStReportErrorAlterApplies)){
                for (SwStReportErrorAlterApply stReportErrorAlterApply : swStReportErrorAlterApplies) {
                    //线网通知报表差错--修改车站的加入报表差错状态 如果datasource == 1 && id == null && dataSourceTable == null
                    //if(!"1".equals(stReportErrorAlterApply.getDataSource())){
                        List<String> sqlList = xwReportMistakeInfoCtrl.stationReprotApply(stReportErrorAlterApply,true);
                        if(CollectionUtil.isNotEmpty(sqlList)){
                            for (String sql : sqlList) {
                                Integer integer = JdbcUtil.exeSqlCrud(sql);
                            }
                        }
                    //}
                }
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }


    /**
     * 获取线路
     * @param param
     * @return
     */
    @RequestMapping("/getLineLists")
    @ApiOperation(value = "获取线路", notes = "获取线路")
    public Result getLineLists(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            List<SwParamLine> reportErrorAlterAppays= reportMistakeInfoServiceImpl.getLineLists(param);
            result.setData(reportErrorAlterAppays);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询线路失败");
        }
        return result;
    }

    /**
     * 获取车站
     * @param page
     * @param param
     * @return
     */
    @RequestMapping("/getStationLists")
    @ApiOperation(value = "获取车站", notes = "获取车站")
    public Result getStationLists( Page page,@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            List<SwParamStation> reportErrorAlterAppays= reportMistakeInfoServiceImpl.getStationLists(param);
            result.setData(reportErrorAlterAppays);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询车站失败");
        }
        return result;
    }
	/**
     * 根据usercode查找车站其他账户信息
     * @param param
     * @return
     */
    @RequestMapping("/getPersonOtherStationLists")
    @ApiOperation(value = "根据usercode查找车站其他账户信息", notes = "根据usercode查找车站其他账户信息")
    public Result getPersonOtherStationLists(Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);		
		PigxUser user = SecurityUtils.getUser();
		String userCode = user.getUserCode();
         try {            
			List<SysUser> sysUsers = sysUserMapper.getPersonOtherStation(userCode);
			log.error("userCode 个人信息----------------=="+userCode+sysUsers.size());
			result.setData(sysUsers);
           
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询用户失败");
        }		
	    return result;
    }


    /**
     * 获取员工的角色
     * @param param
     * @return
     */
    @RequestMapping("/getPersonRole")
    @ApiOperation(value = "获取员工的角色", notes = "获取员工的角色")
    public Result getPersonRoles(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            //获取 值班站长，值班员，站务员，
            List<Map<String,Object>> reportErrorAlterAppays= reportMistakeInfoServiceImpl.getPersonRoles(param);
            result.setData(reportErrorAlterAppays);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询指定角色人员失败");
        }
        return result;
    }

    /**
     * 获取员工的角色
     * @param param
     * @return
     */
    @RequestMapping("/getPersonRoleToLS")
    @ApiOperation(value = "获取员工的角色", notes = "获取员工的角色")
    public List<Map<String, Object>> getPersonRoleToLS(Map<String, String> param) {
        Map<String, Object> p=new HashMap<>();
        Map<String,Object> p2=new HashMap<>();

        if(null != param.get("stationCode") && !"".equals(param.get("stationCode")) && !"null".equals(param.get("stationCode")))
            p2.put("stationCode",param.get("stationCode"));
        if(null != param.get("lineCode") && !"".equals(param.get("lineCode")) && !"null".equals(param.get("lineCode")))
            p2.put("lineCode",param.get("lineCode"));
        List<Map<String, Object>> users=sysRoleMapper.getCurrRoleUsers(p2);
        return users;
    }

    /**
     * 获取报表
     * @param param
     * @return
     */
    @RequestMapping("/getReports")
    @ApiOperation(value = "获取报表", notes = "获取报表")
    public Result getReports(@RequestParam Map<String,String> param){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            List<SwPmReportPath> reportErrorAlterAppays= reportMistakeInfoServiceImpl.getReports(param);
            result.setData(reportErrorAlterAppays);
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            result.appendMsg("查询报表失败");
        }
        return result;
    }

    /**
     * 修改报表
     * @param swStReportErrorAlterApply
     * @return
     */
    @RequestMapping("/updateReport")
    @ApiOperation(value = "修改报表", notes = "修改报表")
    public Result updateReport(SwStReportErrorAlterApply swStReportErrorAlterApply){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            int aff = swStReportErrorAlterAppayMapper.updateById(swStReportErrorAlterApply);
            if(aff==0){
                result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                result.appendMsg("未通知成功");
            }
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            result.appendMsg("修改报表失败");
        }
        return result;
    }

    /**
     * 报表差错审批
     * @param params
     * @return
     */
    @RequestMapping("/updateReportApplyStatus")
    @ApiOperation(value = "报表差错审批", notes = "报表差错审批")
    @Transactional(rollbackFor = Exception.class)
    public Map updateReportApplyStatus(@RequestBody Map<String,Object> params){
        String checkStatus = String.valueOf(params.get("checkStatus"));
        JSONArray ids = JSONObject.parseArray(String.valueOf(params.get("ids")));
        try {
            List<SwStReportErrorAlterApply> reportErrorAlterAppayOne = reportMistakeInfoMapper.selectBatchIds((List) ids);
            for(SwStReportErrorAlterApply swStReportErrorAlterApply : reportErrorAlterAppayOne){
                if(!"2".equals(swStReportErrorAlterApply.getCheckStatus())){
                    continue;
                }
                swStReportErrorAlterApply.setCheckStatus(checkStatus);
                swStReportErrorAlterApply.setUpdateTime(DateFormat.date_ex_str(new Date(),"yyyy-MM-dd HH:mm:ss"));
                reportMistakeInfoMapper.updateById(swStReportErrorAlterApply);
            }
            commonController.innerBatch(params);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        Map resp = new HashMap();
        resp.put("code","1");
        return resp;
    }

    /**
     * 报表差错设定期限
     * @param params
     * @return
     */
    @RequestMapping("/updateReportApplyModifyLimitTime")
    @ApiOperation(value = "报表差错设定期限", notes = "报表差错设定期限")
    public Map updateReportApplyModifyLimitTime(@RequestParam Map<String,String> params){
        JSONArray checkStatus = JSONObject.parseArray(params.get("modifyLimitTimeDatas"));
        //报表差错设定期限
        reportMistakeInfoServiceImpl.updateReportApplyModifyLimitTime(checkStatus);
        Map resp = new HashMap();
        resp.put("code","1");
        return resp;
    }

    /**
     * 获取报表差错设定期限
     * @param params
     * @return
     * @throws SQLException
     */
    @RequestMapping("/getmodifyLimitTime")
    @ApiOperation(value = "获取报表差错设定期限", notes = "获取报表差错设定期限")
    public Result getmodifyLimitTime(@RequestParam Map<String,String> params) throws SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        try {
            List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("select * from sw_pm_report_alter");
            Map<String, Object> map = maps.get(0);
            res.setData(map);
        }catch (Exception e){
            log.error("{}",e);
            Map<String, Object> map =new HashMap<>();
            map.put("alter_limit",0);
            res.setData(map);
        }
        return res;
    }

    /**
     * 导出
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/checkXlsxData")
    @ApiOperation(value = "导出", notes = "导出")
    public Result checkXlsxData(@RequestParam MultipartFile file, HttpServletRequest request){

        Result result=new Result(ResultDetailMsg.OK);
        try {
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Workbook wb=null;
            //根据文件后缀（xls/xlsx）进行判断
            if (fileName.endsWith("xls")){
                wb = new HSSFWorkbook(inputStream);
            }else if (fileName.endsWith("xlsx")){
                wb = new XSSFWorkbook(inputStream);
            }else {
                result.setMsg("请使用xls、xlsx格式文件");
                result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                return result;
            }
            List<Map<String,Object>> list=new ArrayList<>();
            Sheet sheetAt = wb.getSheetAt(0);
            for(int i=0;i<=sheetAt.getLastRowNum();i++){
                Map<String,Object> one=new HashMap<>();
                Row row = sheetAt.getRow(i);
                if(i<1){
                    continue;
                }
                String lineName = ExcelCellUtil.getCellContent(row.getCell(0));// row. map.get("线路");
                String stationName = ExcelCellUtil.getCellContent(row.getCell(1));//map.get("车站");
                String noticeTime = ExcelCellUtil.getCellContent(row.getCell(2));// map.get("通知时间");
                String reprotTime = ExcelCellUtil.getCellContent(row.getCell(3));//map.get("报表时间");
                String reportName =ExcelCellUtil.getCellContent(row.getCell(4));// map.get("报表名称");
                String sheJiPerson = ExcelCellUtil.getCellContent(row.getCell(5));//map.get("涉及人员");
                String remark = ExcelCellUtil.getCellContent(row.getCell(6));//map.get("备注");
                String isModify = ExcelCellUtil.getCellContent(row.getCell(7));//map.get("是否更改");
                String modifyTime = ExcelCellUtil.getCellContent(row.getCell(8));//map.get("更改日期");
                String creatorName = ExcelCellUtil.getCellContent(row.getCell(9));//map.get("更改人");

                one.put("lineName",lineName);
                one.put("stationName",stationName);
                one.put("noticeTime",noticeTime);
                one.put("reprotTime",reprotTime);
                one.put("reportName",reportName);
                one.put("sheJiPerson",sheJiPerson);
                one.put("remark",remark);
                one.put("isModify",isModify);
                one.put("modifyTime",modifyTime);
                one.put("creatorName",creatorName);
                list.add(one);
            }
            JSONObject res=new JSONObject();
            res.put("list",list);
            redisTemplateConfig.redisTemplate().opsForValue().set(UserInfo.getUserCode()+"_report_error"+"_export",res.toJSONString());
            result.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            log.error("文件上传处理失败{}",e);
            result.setMsg("文件上传处理失败");
            result.setResult(ResultDetailMsg.MONDIFY_FILE_FAILD);
        }
        return result;
    }


    /**
     * 报表文件导入
     * @param request
     * @return
     */
    @RequestMapping("/import_report_error")
    @ApiOperation(value = "报表文件导入", notes = "报表文件导入")
    @Transactional(rollbackFor = Exception.class)
    public Result import_report_error(HttpServletRequest request){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            String _export = (String) redisTemplateConfig.redisTemplate().opsForValue().get(UserInfo.getUserCode()+"_report_error"+"_export");
            JSONObject list = JSONObject.parseObject(_export);
            JSONArray jsonArray = list.getJSONArray("list");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String lineName = jsonObject.getString("lineName");
                String stationName = jsonObject.getString("stationName");
                JSONObject sub = LineOrStation.getlinenameOrStationName(lineName, stationName);
                String noticeTime = jsonObject.getString("noticeTime");
                String reprotTime = jsonObject.getString("reprotTime");
                String reportName = jsonObject.getString("reportName");
                String sheJiPerson = jsonObject.getString("sheJiPerson");
                String remark = jsonObject.getString("remark");
                String isModify = jsonObject.getString("isModify");
                String modifyTime = jsonObject.getString("modifyTime");
                String errorAmount = jsonObject.getString("errorAmount");
//                String creatorName = jsonObject.getString("creatorName");

                SwStReportErrorAlterApply swStReportErrorAlterApply=new SwStReportErrorAlterApply();
                swStReportErrorAlterApply.setLineCode(sub.getString("lineCode"));
                swStReportErrorAlterApply.setStationCode(sub.getString("stationCode"));
                swStReportErrorAlterApply.setNoticeTime(DateFormat.panDuanDate(noticeTime));
                swStReportErrorAlterApply.setReprotTime(DateFormat.date_ex_str(DateFormat.panDuanDate(reprotTime)));
                swStReportErrorAlterApply.setErrorClassification("1");
                List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("select id from sw_pm_report_path where report_name='"+reportName+"'");
                if(maps.size()<=0){
                    result.setMsg("未发现【"+reportName+"】报表");
                    result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                    return result;
                }
                swStReportErrorAlterApply.setReportNameId(String.valueOf(maps.get(0).get("id")));
                swStReportErrorAlterApply.setRemark(remark);
                swStReportErrorAlterApply.setIsModify("是".equals(isModify)?"1":"0");
                swStReportErrorAlterApply.setModifyTime(DateFormat.panDuanDate(modifyTime));
                swStReportErrorAlterApply.setErrorAmount(errorAmount==null?"0":errorAmount);
                swStReportErrorAlterApply.setCheckStatus("3");//默认·已通过
                swStReportErrorAlterApply.setDelFlag("0");
                swStReportErrorAlterApply.setApplyReason("");
                swStReportErrorAlterApply.setNoticeStatus("0");
                swStReportErrorAlterApply.setUpdateTime(DateFormat.date_ex_str(new Date()));
                swStReportErrorAlterApply.setDataSource("2");
                swStReportErrorAlterApply.setApplyTime(DateFormat.date_ex_str(new Date()));
                swStReportErrorAlterApply.setErrorDetail("");
                List<Map<String, Object>> alter_limit = JdbcUtil.exeSqlQuery("select alter_limit from sw_pm_report_alter");
                swStReportErrorAlterApply.setModifyLimitTime(Integer.parseInt(alter_limit.get(0).get("alter_limit")+""));
                swStReportErrorAlterApply.setCreatorName(UserInfo.getName());
                swStReportErrorAlterApply.setCreatorId(UserInfo.getId());
                swStReportErrorAlterApply.setCreateTime(DateFormat.date_ex_str(new Date()));
                int aff = swStReportErrorAlterAppayMapper.insertReport(swStReportErrorAlterApply);

                //报表差错更改申请涉及人员（申请人员）
                insertUserCodeToReportDetail(sheJiPerson,swStReportErrorAlterApply.getId());
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("文件上传处理失败{}",e);
            result.setMsg("文件上传处理失败");
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 报表差错更改申请涉及人员（申请人员）
     * @param name
     * @param reloinId
     * @return
     * @throws SQLException
     */
    private Integer insertUserCodeToReportDetail(String name,long reloinId) throws SQLException {

        for(int i=0;i<name.split(",").length;i++){
            JSONObject jsonObject = getUserCode(name.split(",")[i]);
            if(jsonObject.size()<=0){
                continue;
            }
            SwStReportErrorAlterAppayDetail swStReportErrorAlterAppayDetail=new SwStReportErrorAlterAppayDetail();
            swStReportErrorAlterAppayDetail.setRelationid(reloinId);
            swStReportErrorAlterAppayDetail.setStationPersonrId(jsonObject.getInteger("userId"));
            swStReportErrorAlterAppayDetail.setStationPersonrCode(jsonObject.getString("userCode"));
            swStReportErrorAlterAppayDetail.setStationPersonrName(jsonObject.getString("nikename"));
            swStReportErrorAlterAppayDetailMapper.insert(swStReportErrorAlterAppayDetail);
        }
        return 0;
    }

    /**
     * 获取人员信息
     * @param name
     * @return
     * @throws SQLException
     */
    private JSONObject getUserCode(String name) throws SQLException {
        JSONObject jsonObject=new JSONObject();
        List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("select user_id,user_code,nikename from sys_user where nikename ='" + name + "' or user_code='" + name + "'");
        if(maps.size()>0){
            jsonObject.put("userId",maps.get(0).get("user_id"));
            jsonObject.put("userCode",maps.get(0).get("user_code"));
            jsonObject.put("nikename",maps.get(0).get("nikename"));
        }
        return jsonObject;
    }

    /**
     * 收入审核- 修改报表添加
     * @param row
     * @return
     */
    @RequestMapping("/add_cz_sq_ReportError")
    @ApiOperation(value = "收入审核- 修改报表添加", notes = "收入审核- 修改报表添加")
    @Transactional(rollbackFor = Exception.class)
    public Result add_cz_sq_ReportError(String row, String sheJiPersons){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            JSONObject rowJson = JSONObject.parseObject(row);
            SwStReportErrorAlterApply swStReportErrorAlterApply=JSONObject.parseObject(row, SwStReportErrorAlterApply.class);
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            swStReportErrorAlterApply.setApplyTime(dff.format(new Date()));
            swStReportErrorAlterApply.setErrorDetail("");
            swStReportErrorAlterApply.setCheckStatus("3");
            swStReportErrorAlterApply.setCreateTime(dff.format(new Date()));
            Map<String,Object> p1=new HashMap<>();
            p1.put("user_code", UserInfo.getUserCode());
            List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
            swStReportErrorAlterApply.setCreatorName(sysUsers.get(0).getNikename());
            swStReportErrorAlterApply.setCreatorId(UserInfo.getId());
            swStReportErrorAlterApply.setDelFlag("0");
            swStReportErrorAlterApply.setUpdateTime(dff.format(new Date()));
            swStReportErrorAlterApply.setDiffAmountId(rowJson.getInteger("resultIds"));
            swStReportErrorAlterApply.setDataSourceTable(rowJson.getString("operatorTable"));
            if(StringUtils.isEmpty(swStReportErrorAlterApply.getDataSource())){
                swStReportErrorAlterApply.setDataSource("2");//线网
            }
            if(StringUtils.isNotEmpty(swStReportErrorAlterApply.getBomCode())){
                swStReportErrorAlterApply.setBomCode(DateFormat.bomOrJobNoSort(swStReportErrorAlterApply.getBomCode()));//bom编号排序后修改
            }
            //新增报表差错
            int aff = swStReportErrorAlterAppayMapper.insertReport(swStReportErrorAlterApply);

            JSONArray jsonArray = JSONArray.parseArray(sheJiPersons);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                SwStReportErrorAlterAppayDetail swStReportErrorAlterAppayDetail=JSONObject.parseObject(jsonObject.toJSONString(), SwStReportErrorAlterAppayDetail.class);
                swStReportErrorAlterAppayDetail.setRelationid(swStReportErrorAlterApply.getId());
                swStReportErrorAlterAppayDetailMapper.insert(swStReportErrorAlterAppayDetail);
            }
            Integer resultIds=rowJson.getInteger("resultIds");
            String operatorTable=rowJson.getString("operatorTable");
            if(resultIds!=null && org.apache.commons.lang3.StringUtils.isNotEmpty(operatorTable)){
                if(Integer.parseInt(swStReportErrorAlterApply.getDataSource())>2){
                    String sql="update "+operatorTable+" set Is_add_reprot_error=1 where id="+resultIds;
                    JdbcUtil.exeSqlCrud(sql);
                }
            }

        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_INSERT_ERROR);
            result.appendMsg("修改失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 收入审核- 修改报表编辑
     * @param row
     * @return
     */
    @RequestMapping("/update_srsh_sq_ReportError")
    @ApiOperation(value = "收入审核- 修改报表编辑", notes = "收入审核- 修改报表编辑")
    public Result update_srsh_sq_ReportError(String row, String sheJiPersons){
        Result result=new Result(ResultDetailMsg.OK);
        try {
            SwStReportErrorAlterApply swStReportErrorAlterApply=JSONObject.parseObject(row, SwStReportErrorAlterApply.class);
            if(StringUtils.isNotEmpty(swStReportErrorAlterApply.getBomCode())){
                swStReportErrorAlterApply.setBomCode(DateFormat.bomOrJobNoSort(swStReportErrorAlterApply.getBomCode()));//bom编号排序后修改
            }
            int aff = swStReportErrorAlterAppayMapper.updateById(swStReportErrorAlterApply);

            Map<String,Object> param=new HashMap<>();
            param.put("relationid",swStReportErrorAlterApply.getId());
            swStReportErrorAlterAppayDetailMapper.deleteByMap(param);//删除

            JSONArray jsonArray = JSONArray.parseArray(sheJiPersons);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                SwStReportErrorAlterAppayDetail swStReportErrorAlterAppayDetail=JSONObject.parseObject(jsonObject.toJSONString(), SwStReportErrorAlterAppayDetail.class);
                swStReportErrorAlterAppayDetail.setRelationid(swStReportErrorAlterApply.getId());
                swStReportErrorAlterAppayDetailMapper.insert(swStReportErrorAlterAppayDetail);
            }

        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            result.appendMsg("修改失败");
        }
        return result;
    }
}
